const loki = require('lokijs')
const fs = require('fs')
const request = require('superagent');

const cheerio = require('cheerio');
// 启动log
// const log4js = require('log4js');
// log4js.configure({
//     appenders: { cheese: { type: 'file', filename: './GDZJ.log' } },
//     categories: { default: { appenders: ['cheese'], level: 'trace' } }
// });
// const logger = log4js.getLogger('cheese');


var db = new loki('./SD_DB.db', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    autosaveInterval: 4000
});

// implement the autoloadback referenced in loki constructor
function databaseInitialize() {
    var robots = db.getCollection("robots");
    if (robots === null) {
        robots = db.addCollection("robots");
    }
    // kick off any program logic or start listening to external events
    runProgramLogic(robots);
}


function createRobotDB(robots) {
    var robotJSON = JSON.parse(fs.readFileSync('./SDdata.json'))
    robots.insert(robotJSON)
}


var i = 0, mergeCount = 0;
let machineMap = {}
let madchineArr = []


function runProgramLogic(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    startMerge(i)
    function startMerge(i) {
        mergeGundam(res[i])
            .then(data => {
                mergeCount++
                console.log(mergeCount, "条")
                if (mergeCount == res.length) {
                    robots.update(res)
                    console.log('merge gundam完毕')
                    db.save()
                }
                else {
                    // continue
                    i++
                    startMerge(i)
                }
            })
    }



}

function mergeGundam(gundam) {
    return new Promise(function (resolve, reject) {

        gundam.AvatarUrl_TW = `https://www.olgame.tw/sds/images/robot/${gundam.ID}.gif`
        gundam.toMake.forEach(tmp => {
            tmp.img_TW = `https://www.olgame.tw/sds/images/robot/${tmp.id}.gif`
        });
        gundam.makeNeed.forEach(tmp => {
            tmp.img_TW = `https://www.olgame.tw/sds/images/robot/${tmp.id}.gif`
        });
        gundam.makeNeed_CN.forEach(tmp => {
            tmp.img_TW = `https://www.olgame.tw/sds/images/robot/${tmp.id}.gif`
        });

        request.get(`https://www.olgame.tw/sds/robot_detail.php?id=${gundam.ID}`)
            .then(res => {
                const $ = cheerio.load(res.text)
                let nameCN_G = $($('p')[1]).text().trim()
                $($($('p')[3]).find('strong')).remove().text().trim();
                let rushTime = $($('p')[3]).text().trim()
                rushTime = checkType(rushTime)
                $($($('p')[4]).find('strong')).remove().text().trim();
                let jumpTime = $($('p')[4]).text().trim();
                jumpTime = checkType(jumpTime)
                $($($('p')[5]).find('strong')).remove().text().trim();
                let Radar_distance = $($('p')[5]).text().trim();
                Radar_distance = checkType(Radar_distance)
                let expTable = $("[bordercolor='#666699']").html()
                let weaponTable = ""
                $('#myTab1_Content1').find('img').each((index, ele) => {
                    let src = $(ele).attr('src')
                    $(ele).attr('src', `https://www.olgame.tw/sds/${src}`)
                })
                weaponTable = $('#myTab1_Content1').html();
                Object.assign(gundam, {
                    nameCN_G: nameCN_G,
                    rushTime: rushTime,
                    jumpTime: jumpTime,
                    Radar_distance: Radar_distance,
                    expTable: expTable,
                    weaponTable: weaponTable
                })
                console.log(`${gundam.model}获取完毕`)
                resolve(gundam)
            })
            .catch(error => {
                console.log(`${gundam.model}获取失败，重来`)
                mergeGundam(gundam)
            })
    })
}

function checkType(str) {
    if (str.match('R2')) {
        arr = str.split('R2:');
        return 'R1: ' + arr[0].split('R1:')[1].trim().replace('\n', '').replace(' ', '') + ' / R2: ' + arr[1].trim().replace('\n', '').replace(' ', '')
    } else {
        return str;
    }
}

module.exports = db;